package gr.aueb.cs.mscis.chordroid.chord;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

import android.util.Log;

/**
 * This class implements a simple connection
 * to the tracker and starts off the registration
 * procedure of the node
 * @author lupin
 *
 */
public class BootstrapService implements Runnable {
	
	private String trackerAddr = "192.168.2.2";
//	private String trackerAddr = "10.0.9.32";
	private int trackerPort = 6666;
	private ObjectOutputStream oos;
	private ObjectInputStream ois;
	
	/**
	 * the register method
	 * @return
	 */
	public RemoteMessage register() {
		Socket clientSocket;
		try {
			clientSocket = new Socket(trackerAddr, trackerPort);
			oos = new ObjectOutputStream(clientSocket.getOutputStream());
			oos.writeObject(new RemoteMessage(ProtocolType.REGISTER, null, null));
			
			ois = new ObjectInputStream(clientSocket.getInputStream());
			RemoteMessage response = (RemoteMessage) ois.readObject();
					
			clientSocket.close();
			return response;

		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			Log.v("BootstrapService", e.getMessage());
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		return null;
	}

	public void run() {
		register();
	}

}
